#include "HelloWorldScene.h"
#include "editor-support/cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"

USING_NS_CC;

using namespace cocostudio::timeline;

Scene* HelloWorld::createScene()
{
	// 'scene' is an autorelease object
	// 创建一个游戏场景对象
	auto scene = Scene::create();

	// 'layer' is an autorelease object
	// 创建游戏层对象
	auto layer = HelloWorld::create();

	// add layer as a child to scene
	// 层加入到场景中
	scene->addChild(layer);

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
	/**  you can create scene with following comment code instead of using csb file.
	// 1. super init first
	if ( !Layer::init() )
	{
		return false;
	}

	Size visibleSize = Director::getInstance()->getVisibleSize();
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

	/////////////////////////////
	// 2. add a menu item with "X" image, which is clicked to quit the program
	//    you may modify it.

	// add a "close" icon to exit the progress. it's an autorelease object
	auto closeItem = MenuItemImage::create(
										   "CloseNormal.png",
										   "CloseSelected.png",
										   CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));

	closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
								origin.y + closeItem->getContentSize().height/2));

	// create menu, it's an autorelease object
	auto menu = Menu::create(closeItem, NULL);
	menu->setPosition(Vec2::ZERO);
	this->addChild(menu, 1);

	/////////////////////////////
	// 3. add your codes below...

	// add a label shows "Hello World"
	// create and initialize a label

	auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);

	// position the label on the center of the screen
	label->setPosition(Vec2(origin.x + visibleSize.width/2,
							origin.y + visibleSize.height - label->getContentSize().height));

	// add the label as a child to this layer
	this->addChild(label, 1);

	// add "HelloWorld" splash screen"
	auto sprite = Sprite::create("HelloWorld.png");

	// position the sprite on the center of the screen
	sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 + origin.y));

	// add the sprite as a child to this layer
	this->addChild(sprite, 0);
	**/

	//////////////////////////////
	// 1. super init first
	// 1. 初始化层
	if (!Layer::init())
	{
		return false;
	}

	// 获取视窗大小
	Size visibleSize = Director::getInstance()->getVisibleSize();
	// 获取视窗原点
	Vec2 origin = Director::getInstance()->getVisibleOrigin();

#pragma region 文字内容显示  
	// 文字显示  TTF
	auto labelWithTTF = Label::createWithTTF("Hello Cocos", "fonts/Marker Felt.ttf", 24);
	labelWithTTF->setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - labelWithTTF->getContentSize().height);
	labelWithTTF->enableOutline(Color4B::GREEN, 1);
	this->addChild(labelWithTTF, 10);

	// 文字显示  BMFont
	//创建需要显示的字典类
	auto dict = __Dictionary::createWithContentsOfFile("fonts/string.xml");
	auto strStart = dynamic_cast<__String *>(dict->objectForKey("start"));
	auto labelWithBMFont = Label::createWithBMFont("fonts/game.fnt", strStart->getCString());
	labelWithBMFont->setPosition(Vec2(origin.x + labelWithBMFont->getContentSize().width, 240.0f));
	labelWithBMFont->setColor(Color3B::GREEN);
	labelWithBMFont->enableShadow(Color4B::BLUE, Size(5, -5), 10);
	this->addChild(labelWithBMFont, 20);
#pragma endregion TTF&BMFont

#pragma region 精灵
	//生成精灵对象
	//auto sprite = Sprite::create("HelloWorld.png");
	auto sprite = Sprite::create("timg.jpg");
	// 设置位置参数，默认锚点为中央
	sprite->setPosition(Vec2(visibleSize.width / 2 + origin.x, visibleSize.height / 2 + origin.y));
	//加入到层中
	this->addChild(sprite, 0);

	//生成指定区域大小的精灵
	auto spriteRect = Sprite::create("HelloWorld.png", Rect(430, 270, 100, 100));
	spriteRect->setPosition(Vec2(200.0f, 200.0f));
	this->addChild(spriteRect);

	//纹理缓存：提高利用率，提高访问速度。在Cocos2d的一个实例中只存在一个缓冲区
	auto textureCache = Director::getInstance()->getTextureCache()->addImage("HelloWorld.png");
	auto spriteWithTexture = Sprite::create();
	spriteWithTexture->setTexture(textureCache);
	spriteWithTexture->setTextureRect(Rect(300, 400, 100, 100));
	spriteWithTexture->setPosition(Vec2(10.0f, 200.0f));
	this->addChild(spriteWithTexture);

	//精灵帧缓存：利用合图（TexturePackerGUI）技术来实现
	SpriteFrameCache::getInstance()->addSpriteFramesWithFile("blueman.plist");
	auto blueman = Sprite::createWithSpriteFrameName("L05.png");
	blueman->setPosition(Vec2(700.0f, 200.0f));
	this->addChild(blueman);

#pragma endregion 图片文件/图片文件+区域/纹理缓存/精灵帧缓存

#pragma region 精灵菜单类
	auto closeMenuItem = MenuItemImage::create("close_normal.png", "close_selected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this));
	closeMenuItem->setPosition(Vec2(origin.x + visibleSize.width - closeMenuItem->getContentSize().width / 2, origin.y + closeMenuItem->getContentSize().height / 2));
	auto menu = Menu::create(closeMenuItem, NULL);
	menu->setPosition(Vec2::ZERO);
	this->addChild(menu);

#pragma endregion 

#pragma region 动作(Action)演示
	//blueman->runAction(MoveBy::create(2,Vec2(50,50)));
	//贝塞尔曲线动作
	ccBezierConfig bezier;
	bezier.controlPoint_1 = Vec2(0,visibleSize.height);
	bezier.controlPoint_2 = Vec2(300, -visibleSize.height);
	bezier.endPosition = Vec2(300, 300);
	blueman->runAction(RepeatForever::create(
		Spawn::create(
			BezierTo::create(4.0, bezier), 
			RotateBy::create(3.0, 180),
			NULL
		)
	));

	//精灵帧动画
	Vector<SpriteFrame *> animationFrames;
	char str[100] = {0};
	for (int i = 1; i < 8; ++i) {
		sprintf(str, "L0%d.png", i);
		auto frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(str);
		animationFrames.pushBack(frame);
	}
	auto animation = Animation::createWithSpriteFrames(animationFrames, 0.3f);
	blueman->runAction(RepeatForever::create(Animate::create(animation)));
#pragma endregion 重复(贝塞尔曲线并行旋转) / 精灵帧动画

#pragma region 鼠标事件处理
	auto  mouseListener = EventListenerMouse::create();
	mouseListener->onMouseMove = [](Event *event)
	{
		auto e = dynamic_cast<EventMouse*>(event);
		log("X:%f, Y:%f", e->getCursorX(), e->getCursorY());
	};
	mouseListener->onMouseDown = [](EventMouse *event)
	{
		log("Mouse Key : %i", event->getMouseButton());
	};
	//注册事件
	_eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener ,this);

#pragma endregion 
	 
	return true;
}

void HelloWorld::menuCloseCallback(Ref* pSender) {
	//关闭游戏
	//停止定时器
	unscheduleUpdate();
	//结束
	Director::getInstance()->end();
#if(CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
	exit(0);
#endif
}